import { _decorator, Component, Label, ProgressBar, resources, Sprite, SpriteFrame, UITransform } from 'cc';
import { EntityType, UnitType, BuildingType, PlayerType } from '../../../battle/Enums';
import { UnitModel, BuildingModel } from '../../../battle/Model';
import { BuildingConfig, UnitConfig } from 'db://assets/battle/Const';
import { ResourceLoadManager } from '../render/ResourceLoadManager';
import { LOG } from '../../../ConsoleLogCtrl';
const { ccclass, property } = _decorator;

/**
 * 实体数据接口
 */
export interface IEntityData {
    id: number;
    playerType: PlayerType,
    type: EntityType;
    unitType?: UnitType;
    buildingType?: BuildingType;
    player: string;
    hp: number;
    maxHp: number;
    attack?: number;
    speed?: number;
    position: {
        x: number;
        y: number;
    };
    additionalInfo?: string;
}

/**
 * 实体统计项目组件
 * 用于显示单个实体的类型、血量和信息内容
 */
@ccclass('EntityStatsItem')
export class EntityStatsItem extends Component {

    // 实体类型标签
    @property(Sprite)
    public entityType: Sprite = null;

    // 实体类型名称
    @property(Label)
    public entityTypeName: Label = null;

    // 血量标签
    @property(Label)
    public hpLabel: Label = null;

    // 血量进度条
    @property(ProgressBar)
    public hpProgressBar: ProgressBar = null;

    // 附加信息标签
    @property(Label)
    public additionalInfoLabel: Label = null;

    // 当前实体数据
    private _entityData: IEntityData = null;

    onLoad() {
        this.initLabels();
    }

    /**
     * 初始化标签组件
     * 如果没有手动绑定，则自动查找子节点中的Label组件
     */
    private initLabels() {
        if (!this.entityTypeName) {
            const entityTypeNameNode = this.node.getChildByName('typeName');
            if (entityTypeNameNode) {
                this.entityTypeName = entityTypeNameNode.getComponent(Label);
            }
        }

        const hpNode = this.node.getChildByName('hp');
        if (!this.hpLabel) {
            if (hpNode) {
                this.hpLabel = hpNode.getChildByName('Label').getComponent(Label);
            }
        }

        if (!this.hpProgressBar) {
            if (hpNode) {
                this.hpProgressBar = hpNode.getChildByName('ProgressBar').getComponent(ProgressBar);
            }
        }

        if (!this.additionalInfoLabel) {
            const additionalInfoNode = this.node.getChildByName('info');
            if (additionalInfoNode) {
                this.additionalInfoLabel = additionalInfoNode.getComponent(Label);
            }
        }
    }

    /**
     * 设置实体数据
     * @param entityData 实体数据
     */
    public async setEntityData(entityData: IEntityData) {
        this._entityData = entityData;
        await this.updateDisplay();
    }

    /**
     * 从单位模型创建实体数据
     * @param unitModel 单位模型
     * @param playerType 玩家类型
     * @returns 实体数据
     */
    public static createFromUnitModel(playerType: PlayerType, unitModel: UnitModel): IEntityData {
        return {
            id: unitModel.id,
            playerType: playerType,
            type: EntityType.unit,
            unitType: unitModel.type,
            player: unitModel.player,
            hp: unitModel.hp || 0,
            maxHp: UnitConfig[unitModel.type].hp,
            attack: unitModel.attack,
            speed: unitModel.speed,
            position: unitModel.position
        };
    }

    /**
     * 从建筑模型创建实体数据
     * @param buildingModel 建筑模型
     * @param playerType 玩家类型
     * @returns 实体数据
     */
    public static createFromBuildingModel(playerType: PlayerType, buildingModel: BuildingModel): IEntityData {
        return {
            id: buildingModel.id,
            playerType: playerType,
            type: EntityType.building,
            buildingType: buildingModel.type,
            player: buildingModel.player,
            hp: buildingModel.hp || 0,
            maxHp: BuildingConfig[buildingModel.type].hp,
            attack: buildingModel.attack,
            position: buildingModel.position
        };
    }

    /**
     * 获取实体数据
     * @returns 当前实体数据
     */
    public getEntityData(): IEntityData {
        return this._entityData;
    }

    /**
     * 更新显示内容
     */
    private updateDisplay() {
        if (!this._entityData) {
            return;
        }

        // 更新单位类型
        if (this.entityType) {
            this.getEntityTypeSpriteFram();
        }

        // 更新实体类型名称
        if (this.entityTypeName) {
            if (this._entityData.type === EntityType.unit) {
                this.entityTypeName.string = `${UnitConfig[this._entityData.unitType].name}`;
            } else if (this._entityData.type === EntityType.building) {
                this.entityTypeName.string = `${BuildingConfig[this._entityData.buildingType].name}`;
            }
        }

        // 更新血量
        if (this.hpLabel) {
            this.hpLabel.string = `${this._entityData.hp}/${this._entityData.maxHp}`;
        }

        // 更新血量进度条
        if (this.hpProgressBar) {
            const hpRatio = this._entityData.hp / this._entityData.maxHp;
            this.hpProgressBar.progress = Math.max(0, Math.min(1, hpRatio));
        }

        // 更新附加信息
        if (this.additionalInfoLabel) {
            let str = `ID: ${this._entityData.id}  位置: (${this._entityData.position.x},${this._entityData.position.y})`;
            this.additionalInfoLabel.string = str;
            this.additionalInfoLabel.node.active = true;
        }
    }

    /**
     * 获取实体类型精灵帧
     * @returns 实体类型精灵帧
     */
    private getEntityTypeSpriteFram(){
        if (!this.entityType) {
            return;
        }

        if (this._entityData.type === EntityType.unit) {
            this.entityType.spriteFrame = ResourceLoadManager.getUnitIcon(this._entityData.unitType || UnitType.soldier, this._entityData.playerType);

        } else if (this._entityData.type === EntityType.building) {
            this.entityType.spriteFrame = ResourceLoadManager.getBuildingSpriteFrame(this._entityData.buildingType, this._entityData.playerType);
        } else {
            // 默认使用士兵图片
            this.entityType.spriteFrame = ResourceLoadManager.getUnitIcon(UnitType.soldier, this._entityData.playerType);
        }
        let trans = this.entityType.node.getComponent(UITransform);
        trans.setContentSize(32,32)
    }

    /**
     * 更新血量
     * @param newHp 新的血量值
     */
    public updateHp(newHp: number) {
        if (this._entityData) {
            this._entityData.hp = newHp;

            // 更新血量显示
            if (this.hpLabel) {
                this.hpLabel.string = `${this._entityData.hp}/${this._entityData.maxHp}`;
            }

            // 更新血量进度条
            if (this.hpProgressBar) {
                const hpRatio = this._entityData.hp / this._entityData.maxHp;
                this.hpProgressBar.progress = Math.max(0, Math.min(1, hpRatio));
            }
        }
    }

    /**
     * 设置实体图片
     * @param spriteFrame 精灵帧
     */
    public setEntitySprite(spriteFrame: SpriteFrame) {
        if (this.entityType && spriteFrame) {
            this.entityType.spriteFrame = spriteFrame;
        }
    }

    /**
     * 异步设置实体图片（根据当前实体数据）
     */
    public updateEntitySprite() {
        if (this._entityData && this.entityType) {
            this.getEntityTypeSpriteFram();
        }
    }

    /**
     * 设置附加信息
     * @param info 附加信息内容
     */
    public setAdditionalInfo(info: string) {
        if (this._entityData) {
            this._entityData.additionalInfo = info;

            // 更新附加信息显示
            if (this.additionalInfoLabel) {
                if (info) {
                    this.additionalInfoLabel.string = info;
                    this.additionalInfoLabel.node.active = true;
                } else {
                    this.additionalInfoLabel.node.active = false;
                }
            }
        }
    }

    /**
     * 检查实体是否存活
     * @returns 是否存活
     */
    public isAlive(): boolean {
        return this._entityData && this._entityData.hp > 0;
    }

    /**
     * 重置组件状态
     */
    public reset() {
        this._entityData = null;

        // 重置所有标签显示
        if (this.hpLabel) this.hpLabel.string = '';
        if (this.entityTypeName) this.entityTypeName.string = '';
        if (this.hpProgressBar) this.hpProgressBar.progress = 0;
        if (this.additionalInfoLabel) {
            this.additionalInfoLabel.string = '';
            this.additionalInfoLabel.node.active = false;
        }

        // 重置实体图片
        if (this.entityType) {
            this.entityType.spriteFrame = null;
        }
    }
}